//试图通过动态执行函数获取当前对方发送过来的信息
import {default as contract} from 'truffle-contract'
import create_users from '../../build/contracts/CreateUsers.json';
var  User = contract(create_users);
User.setProvider(web3.currentProvider);
var NodeRSA = require("node-rsa");
window.privatekey='';
var myVar = setInterval(getLastInf,4000)
var locAdd;
async function getLastInf() {
    //获取私钥，通过前台
    privatekey = document.getElementById('prikey').value;
    locAdd = (await getAcc())[0];
    try {
        if (privatekey){
            addLatInf(privatekey,locAdd);
        }else{
            document.getElementById("encode").style.display="block";
            encryptFlag =1;
        }

    }catch(e)
    {
        console.log("waiting......")
    }
    

}

//获取实时数据，这种信息暂时不考虑加密
var message = ''; //当前实时信息内容
var blockN; //当前区块号
function addLatInf(privatekey,locAdd){
    var historyInf ={
        'sender':'',
        'time':'',
        'notes':'',
        'receiver':''
    }
    var event;//获得实时数据
    var notes;
    var number;


    User.deployed().then( function (i) {
        i.getPastEvents('NewNote', {fromBlock: 'latest', toBlock: 'latest'}).then( async (data) => {
            event = data;
            // console.log("event:",event)
            // // console.log('信息长度：',event.length)
            // number = event.length;
            // console.log(number,event)
            var checkone = receiver.toLowerCase();
            var add_b = event[0]['args'][0].toLowerCase();
                //注意，一定要注意地址的大小写。
            var add_a = event[0]['args'][2].toLowerCase();

            if ((checkone !=='') && (checkone === add_b) && (locAdd === add_a)){
                if (message != event[0]['args'][1]){
                    historyInf['sender'] = event[0]['args'][0];
                    notes = event[0]['args'][1];
                    notes = decryptprivate(privatekey,notes);
                    //获取当前区块时间戳
                    blockN = event[0]['blockNumber']
                    var t = await getTime(event[0]['blockNumber']);
                    var time = timestampToTime(t['timestamp']);
                    historyInf['time'] = time;
                    historyInf['notes'] = notes;
                    historyInf['receiver'] = event[0]['args'][2];
                    // console.log('historyInf:',historyInf)
                    //历史信息添加
                    var li  = document.createElement('li');
                    li.setAttribute('id','liAdd'+InfNumber);
                    li.setAttribute('class','inf li_left');
                    li.innerText = historyInf['notes'];
                    li.style.cssText = "float:left;margin-left: 80px;color: #0AD5C1;";
                    var div = document.createElement("div")
                    div.style.cssText = "color:red";
                    div.style.fontSize ='5px';//调整字体大小
                    div.innerText = historyInf['time'];
                    li.appendChild(div);
                    document.getElementById('ul').appendChild(li);
                    InfNumber++;
                    // console.log("history:",historyInf)
                }
                message = event[0]['args'][1];
            }

            //删除历史记录按钮
            // var gE = document.getElementById('getEvent');
            // gE.style.cssText = "display:none"
        });
    });
};

// clearInterval(myVar); //暂停执行
//获取当前用户地址
function getTime(number){
    return new Promise(async (resolve,reject)=>{
        await web3.eth.getBlock(number,(err,res)=>{
            resolve(res);
        });

    })
}
function getAcc() {
    return new Promise(async (resolve, reject)=>{
        await web3.eth.getAccounts((err,res)=>{
            resolve(res)
            }
        )
    })
};
/*时间显示操作，五分分钟以内的聊天信息，时间不显示*/
async function getTimeIn5Mine() {
    var t1 = (new Date()).getTime();
    var t2 = (await getTime(blockN))['timestamp'];

    console.log(t1)
    console.log(t2)

    var time = (t1-t2*1000);
    console.log('time',time/60000)

}
getTimeIn5Mine();

//私钥解密
window.decryptprivate = function(privatekey,message) {
    //私钥解密
    var key = new NodeRSA(privatekey);
    key.setOptions({ encryptionScheme: 'pkcs1' });
    message = key.decrypt(message,'utf8')
    // console.log("解密后的数据：",message)
    return message;
}